package com.zjy.common.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @author yxb
 * create_time: 2024-10-21 15:15
 * description: 图像操作工具类
 */
@Slf4j
public class ImageUtils {

    // 图片类型
    private static List<String> IMG_TYPE = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp");

    /**
     * 图片压缩
     *
     * @param imageFile
     */
    @SneakyThrows
    public static void zipImage(File imageFile) {
        // 获取图片类型
        if (!isImageFile(imageFile.getName())) {
            log.info("非图片不处理 {}", imageFile.getName());
            return;
        }
        BufferedImage originalImage = ImageIO.read(imageFile);
        // 获取原始图片的宽度和高度
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        // 创建一个新的 BufferedImage 对象
        BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaledImage.createGraphics();

        // 设置抗锯齿和图像平滑
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制缩放后的图像
        g2d.drawImage(originalImage, 0, 0, width, height, null);
        g2d.dispose();

        ImageIO.write(scaledImage, getFileExtension(imageFile.getName()), imageFile);
    }

    /**
     * 判断文件是否为图片文件
     *
     * @param fileName
     * @return
     */
    public static boolean isImageFile(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return false;
        }

        // 获取文件扩展名并转换为小写
        String extension = getFileExtension(fileName).toLowerCase();

        // 检查文件扩展名是否在图片扩展名列表中
        return IMG_TYPE.contains(extension);
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 文件扩展名如果文件名为空或没有扩展名，则返回空字符串
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }

        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == fileName.length() - 1) {
            return "";
        }

        return fileName.substring(lastDotIndex + 1);
    }
}
